# coding=utf-8

import json
from game.util.RedisManager import RedisManager

# 玩家状态
USER_STATE = {
    "U_STATE_IN_DA_TING": 2,
    "U_STATE_IN_GAME": 3
}

class User:

    def __init__(self, name, user_id, session_id="", md5_password=""):
        self.user_id = user_id
        self.username = name
        self.gender = 0
        self.register_date = 0
        self.session_id = session_id
        self.state = -1
        self.is_playing = True  # 是否正在进行游戏
        self.online = True   # 是否在线
        self.md5_password = md5_password
        self.redis_manager = RedisManager()
        self.reconnect = False
        self.total_loss_point = 0
        self.total_win_point = 0
        self.point = 0
        x = session_id.split(",")
        self.dynamic_id = [x[0], int(x[1])] if len(x)==2 and x[1] else None
        self.is_robot = 0

    def __eq__(self, other):
        if not other:
            return False
        return self.user_id == other.user_id and self.username == other.username

    def update_user_info(self, user_info=None):

        if user_info is None:
            user_info = self.redis_manager.get_client().hgetall("huser:%d"%self.userid)
        self.point = int(user_info.get("point"))
        self.total_loss_point = int(user_info.get("total_loss_point"))
        self.total_win_point = int(user_info.get("total_win_point"))
        self.username = user_info.get("username","default_name")
        self.register_date = user_info.get("register_date", 0)
        self.gender = user_info.get("gender",0)
        self.is_robot = int(user_info.get("is_robot",0))


    def change_point(self, change_point):
        self.point += change_point
        if change_point >=0:
            self.total_win_point += change_point
        else:
            self.total_loss_point += change_point

    def __str__(self):
        return "(name:%s, id:%s, session_id:%s) " % (self.username, self.user_id, self.session_id)

    def to_json(self):
        to_game={
            "user_id":self.user_id, "point": self.point, "gender": self.gender,
            "total_loss_point": self.total_loss_point, "total_win_point": self.total_win_point
        }

        return json.dumps(to_game)

    def to_dict(self):
        to_game = {
            "user_id": self.user_id, "point": self.point, "gender": self.gender,
            "total_loss_point": self.total_loss_point, "total_win_point": self.total_win_point
        }
        return to_game

